package com.lych.dubbo.utils;

import com.lych.model.mongo.Friend;
import com.lych.model.mongo.MovementTimeline;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存好友数据与时间线数据
     * @param userId 用户id
     * @param id    动态id
     */
    @Async
    public void saveTimeLine(Long userId, ObjectId id) {
        //查询好友数据
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //根据好友数据，构建时间线
        for (Friend friend : friends) {
            MovementTimeline mt = new MovementTimeline();
            mt.setCreated(System.currentTimeMillis());
            mt.setMovementId(id);
            mt.setUserId(friend.getUserId());
            mt.setFriendId(friend.getFriendId());
            //保存时间线表
            mongoTemplate.save(mt);
        }
    }
}
